<template>
  <el-input
    clearable
    v-model="keyword"
    placeholder="Search..."
    class="search-box"
    @keyup.enter="updateSearchQuery"
    @clear="handleClear"
  >
    <template #prefix>
      <el-icon class="el-input__icon"><search /></el-icon>
    </template>
  </el-input>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { debounce } from 'lodash-es' // 使用lodash的debounce函数
import { Search } from '@element-plus/icons-vue'

// 使用Vue Router的组合式API
const router = useRouter()
const route = useRoute()

// 初始化搜索关键词，基于当前的route query
const keyword = ref<string>((route.query.keyword as string) || '')

// 监听关键词变化，并更新路由查询参数
const updateSearchQuery = () => {
  router.push({
    path: route.path,
    query: {
      ...route.query,
      keyword: keyword.value || undefined
    }
  })
}

const debouncedUpdateQuery = debounce(updateSearchQuery, 300) // 使用debounce延迟更新

const handleClear = () => {
  keyword.value = ''
  updateSearchQuery()
}

// 监听路由变化，并同步搜索框中的关键词
watch(
  () => route.query.keyword,
  (newKeyword) => {
    keyword.value = (newKeyword as string) || ''
  }
)
</script>

<style scoped>
.search-box {
  width: 300px;
}
</style>
